package org.example.config;

import org.example.filter.JwtAuthenticationTokenFilter;
import org.example.service.impl.AccessDeniedHandlerImpl;
import org.example.service.impl.AuthenticationEntryPointImpl;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

/**
 * @author Rommel
 * @version 1.0
 * @date 2023/6/13-19:01
 * @description TODO
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled =true)
public class CustomWebSecurityConfigurer extends WebSecurityConfigurerAdapter {

    @Resource
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
    @Resource
    private AuthenticationEntryPointImpl authenticationEntryPointImpl;
    @Resource
    private AccessDeniedHandlerImpl accessDeniedHandlerImpl;


    @Override
    protected void configure(HttpSecurity http) throws Exception {

        //禁用 csrf
        http.cors().and().csrf().disable()
                .authorizeRequests()
                //允许以下请求
                .antMatchers("/sys/login").anonymous()
                //所有请求需要身份认证
                .anyRequest().authenticated();
        //把token校验过滤器添加到过滤器链中
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
        http.exceptionHandling().authenticationEntryPoint(authenticationEntryPointImpl);
        http.exceptionHandling().accessDeniedHandler(accessDeniedHandlerImpl);

    }

}
